package com.repro.baselib.lib_base.network.converterFactorys;

import com.future.retronet.RetroBean;
import com.future.retronet.RetroException;
import com.future.retronet.uitls.ParameterizedTypeImpl;
import com.google.gson.Gson;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

public class GsonResponseConverterFactory<T> implements Converter<ResponseBody, T> {

    private Gson gson;
    private Type type;
    private Annotation[] annotations;

    public GsonResponseConverterFactory(Gson gson, Type type, Annotation[] annotations) {
        this.gson = gson;
        this.type = type;
        this.annotations = annotations;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        try {
            if (type.toString().contains("RetroBean")) {
                RetroBean<T> baseBean = gson.fromJson(response, type);
                if (!baseBean.isSuccess()) {
                    throw new RetroException(baseBean.getCode(), baseBean.getMessage());
                }
                return (T) baseBean;
            }

//            ByteArrayInputStream in = new ByteArrayInputStream(response.getBytes("UTF-8"));
//            //解析成需要的对象
//            TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));//根据type获取
//            JsonReader jsonReader = gson.newJsonReader(new InputStreamReader(in, "UTF-8"));
//            T result = (T) adapter.read(jsonReader);
//            if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
//                throw new RetroException(RetroCode.CODE_PARSE_ERR, "JSON document was not fully consumed.");
//            }
//            return result;

            //Type
            ParameterizedTypeImpl p = new ParameterizedTypeImpl(new Type[]{type}, RetroBean.class, RetroBean.class);
            //生成对应RetroBean<T> 通过Parameterized构造一个RetroBean对象
            RetroBean<T> baseBean = gson.fromJson(response, p); //使用GSON反序列化响应
            if (!baseBean.isSuccess()) {
                throw new RetroException(baseBean.getCode(), baseBean.getMessage());
            }
            return (T) baseBean.getData();

        } finally {
            value.close();
        }
    }

}
